import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/album_service.dart';
import 'package:flutter_oldman_health/models/album_data_model.dart';
import 'package:flutter_oldman_health/models/response_data_model.dart';
import 'package:flutter_oldman_health/utils/utils.dart';
import 'package:flutter_oldman_health/widget/common_container.dart';
import 'package:photo_view/photo_view.dart';

class PhotoViewPage extends StatefulWidget {
  PhotoModel img;
  String creator;
  List<PhotoModel> photoList;

  PhotoViewPage(this.photoList, this.img, this.creator);

  @override
  State<StatefulWidget> createState() {
    return PhotoViewPageState();
  }
}

class PhotoViewPageState extends State<PhotoViewPage> {
  Size screenSize;
  PageController pageController;
  PhotoModel currentImg;

  @override
  void initState() {
    super.initState();
    int index = 0;
    currentImg = widget.img;

    if (widget.photoList.length > 0) {
      index = widget.photoList.indexOf(widget.img);
    }

    pageController = PageController(
        initialPage: index, keepPage: false, viewportFraction: 1);
  }

  @override
  Widget build(BuildContext context) {
    screenSize = MediaQuery.of(context).size;

    return Scaffold(
        body: Stack(children: [
      Center(
          child: PageView(
              onPageChanged: (i) {
                setState(() {
                  currentImg = widget.photoList[i];
                });
              },
              scrollDirection: Axis.horizontal,
              reverse: false,
              controller: pageController,
              children: getPhotoPageList())),
      //   [Container(color: Colors.red, child: Text("我是页面0")),
      // Container(color: Colors.green, child: Text("我是页面2"))]
      _arrowBack(context),
      _deleteText(context, currentImg.id),
      _photoInfo(context, currentImg)
    ]));
  }

  List<Widget> getPhotoPageList() {
    return widget.photoList.map((e) {
      return getPhotoView(e);
    }).toList();
  }

  Widget getPhotoView(PhotoModel img) {
    return PhotoView(
        // imageProvider: AssetImage("assets/large-image.jpg"),
        imageProvider: NetworkImage(img.location),
        loadingBuilder: (context, event) {
          if (event == null) {
            return CommonContainer.loadingView();
          }
          final value = event.cumulativeBytesLoaded /
              (event.expectedTotalBytes ?? event.cumulativeBytesLoaded);
          final percentage = (100 * value).floor();
          return Center(
            child: Text("$percentage%"),
          );
        });
  }

  Widget _arrowBack(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          Navigator.pop(context);
        },
        child: Container(
            padding: EdgeInsets.only(top: 46, left: 20),
            child: Icon(Icons.arrow_back_ios, color: Colors.white, size: 24)));
  }

  _delete(String id) {
    print("wwwwwwww");
    // AlbumService.deletePhoto(id).then((value) {
    //   if (value != null && value.statusCode == 200) {
    //     ResponseDataModel data = ResponseDataModel.fromJson(value.data);
    //     if (data != null && data.success()) {
    //       Navigator.pop(context, 10010);
    //     } else {
    //       EasyLoading.showInfo(data.msg);
    //     }
    //   }
    // });
  }

  Widget _photoInfo(BuildContext context, PhotoModel img) {
    String date = formatDate(DateTime.fromMillisecondsSinceEpoch(img.inDate),
        [yyyy, "年", mm, "月", dd, "日"]);

    return Align(
        alignment: Alignment.bottomCenter,
        child: Container(
            padding: EdgeInsets.all(10),
            width: screenSize.width,
            height: 70,
            child:
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text("来自:${widget.creator}",
                  style: TextStyle(fontSize: 16, color: Colors.white)),
              Text("日期:$date",
                  style: TextStyle(fontSize: 16, color: Colors.white))
            ])));
  }

  Widget _deleteText(BuildContext context, String id) {
    return ("我" == widget.creator)
        ? Align(
            alignment: Alignment.topRight,
            child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  showRemindDialog(context, _delete(id), id);
                },
                child: Container(
                    padding: EdgeInsets.only(
                        top: 46, right: 28, left: 16, bottom: 8),
                    child: Text("删除",
                        style: TextStyle(color: Colors.white, fontSize: 18)))))
        : Padding(padding: EdgeInsets.all(8));
  }

  Future showRemindDialog(
      BuildContext context, Function() callback, String id) async {
    var result = await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
              title: Text("删除照片"),
              content: Text("确定删除当前照片？"),
              actions: <Widget>[
                ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child:
                        Padding(padding: EdgeInsets.all(8), child: Text("取消")),
                    style: ButtonStyle(
                      shape: MaterialStateProperty.all(StadiumBorder(
                          side: BorderSide(
                              //设置 界面效果 圆角弧度
                              style: BorderStyle.solid,
                              color: Colors.grey[400]))),
                      foregroundColor:
                          MaterialStateProperty.all(Color(0xff333333)),
                      backgroundColor: MaterialStateProperty.all(Colors.white),
                      textStyle:
                          MaterialStateProperty.all(TextStyle(fontSize: 17)),
                    )),
                ElevatedButton(
                    onPressed: () async {
                      // callback;
                      AlbumService.deletePhoto(id).then((value) {
                        if (value != null && value.statusCode == 200) {
                          ResponseDataModel data =
                              ResponseDataModel.fromJson(value.data);
                          if (data != null && data.success()) {
                            Navigator.pop(context);
                            Navigator.pop(context, 10010);
                          } else {
                            EasyLoading.showInfo(data.msg);
                          }
                        }
                      });
                    },
                    child:
                        Padding(padding: EdgeInsets.all(8), child: Text("确定")),
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.orange),
                        textStyle:
                            MaterialStateProperty.all(TextStyle(fontSize: 17)),
                        shape: MaterialStateProperty.all(StadiumBorder(
                            side: BorderSide(
                          //设置 界面效果 圆角弧度
                          style: BorderStyle.solid,
                          color: Color(0xffFF7F24),
                        )))))
              ]);
        });
    return result;
  }
}
